<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="IM,TrieTree," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言
最近这段时间确实有点忙，这篇的目录还是在飞机上敲出来了的。

言归正传，上周更新了 cim 第一版：为自己搭建一个分布式 IM(即时通讯) 系统；没想到反响热烈，最高时上了 GitHub Trending  Java 版块的首位，一天收到了 300+ 的 star。">
<meta property="og:type" content="article">
<meta property="og:title" content="为自己搭建一个分布式 IM 系统二【从查找算法聊起】">
<meta property="og:url" content="http://crossoverjie.top/2019/01/14/netty/cim02-v1.0.1/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言
最近这段时间确实有点忙，这篇的目录还是在飞机上敲出来了的。

言归正传，上周更新了 cim 第一版：为自己搭建一个分布式 IM(即时通讯) 系统；没想到反响热烈，最高时上了 GitHub Trending  Java 版块的首位，一天收到了 300+ 的 star。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c30496c13.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c30806550.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c30e47d95.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c310cb796.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3128f910.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3143be05.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c315b6c17.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c317b8636.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c31d716d4.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c31f4438c.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c320d9a62.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c323439df.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c32569b6e.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c32ac3397.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c331b88d5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c333b6dad.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c33583002.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c33edb7ef.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c340d4dd9.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c34277179.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c349dd2bb.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c34d8ea29.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c350b56da.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c356cb710.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3646e24c.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3699d6da.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c36e26b18.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3740223e.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c37724b46.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c3816b687.jpg">
<meta property="og:updated_time" content="2019-05-07T17:43:14.972Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="为自己搭建一个分布式 IM 系统二【从查找算法聊起】">
<meta name="twitter:description" content="前言
最近这段时间确实有点忙，这篇的目录还是在飞机上敲出来了的。

言归正传，上周更新了 cim 第一版：为自己搭建一个分布式 IM(即时通讯) 系统；没想到反响热烈，最高时上了 GitHub Trending  Java 版块的首位，一天收到了 300+ 的 star。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1c30496c13.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2019/01/14/netty/cim02-v1.0.1/"/>

  <title> 为自己搭建一个分布式 IM 系统二【从查找算法聊起】 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                为自己搭建一个分布式 IM 系统二【从查找算法聊起】
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2019-01-14T00:08:14+08:00" content="2019-01-14">
              2019-01-14
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/" itemprop="url" rel="index">
                    <span itemprop="name">Netty</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Netty/cim/" itemprop="url" rel="index">
                    <span itemprop="name">cim</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2019/01/14/netty/cim02-v1.0.1/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2019/01/14/netty/cim02-v1.0.1/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2019/01/14/netty/cim02-v1.0.1/" class="leancloud_visitors" data-flag-title="为自己搭建一个分布式 IM 系统二【从查找算法聊起】">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1c30496c13.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><blockquote>
<p>最近这段时间确实有点忙，这篇的目录还是在飞机上敲出来了的。</p>
</blockquote>
<p>言归正传，上周更新了 <a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">cim</a> 第一版：<a href="https://crossoverjie.top/2019/01/02/netty/cim01-started/">为自己搭建一个分布式 IM(即时通讯) 系统</a>；没想到反响热烈，最高时上了 <code>GitHub Trending  Java</code> 版块的首位，一天收到了 300+ 的 star。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c30806550.jpg" alt=""></p>
<a id="more"></a>
<p>现在总共也有 1.3K+ 的 star，有几十个朋友参加了测试，非常感谢大家的支持。</p>
<p>在这过程中也收到一些 <code>bug</code> 反馈，<code>feature</code> 建议；因此这段时间我把一些影响较大的 bug 以及需求比较迫切的 <code>feature</code> 调整了，本次更新的 <code>v1.0.1</code> 版本：</p>
<ul>
<li>客户端超时自动下线。</li>
<li>新增 <code>AI</code> 模式。</li>
<li>聊天记录查询。</li>
<li>在线用户前缀模糊匹配。</li>
</ul>
<p>下面谈下几个比较重点的功能。</p>
<p><code>客户端超时自动下线</code> 这个功能涉及到客户端和服务端的心跳设计，比较有意思，也踩了几个坑；所以准备留到下次单独来聊。</p>
<h1 id="AI-模式"><a href="#AI-模式" class="headerlink" title="AI 模式"></a>AI 模式</h1><p>大家应该还记得这个之前刷爆朋友圈的 <code>估值两个一个亿的 AI 核心代码</code>。</p>
<p>和我这里的场景再合适不过了。</p>
<p>于是我新增了一个命令用于一键开启 AI 模式，使用情况大概如下。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c30e47d95.jpg" alt=""></p>
<p>欢迎大家更新源码体验，融资的请私聊我🤣。</p>
<h1 id="聊天记录"><a href="#聊天记录" class="headerlink" title="聊天记录"></a>聊天记录</h1><p>聊天记录也是一个比较迫切的功能。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c310cb796.jpg" alt=""></p>
<p>使用命令 <code>:q 关键字</code> 即可查询与个人相关的聊天记录。</p>
<p>这个功能其实比较简单，只需要在消息发送及接收消息时保存即可。</p>
<p>但要考虑的一点是，这个保存消息是 IO 操作，不可避免的会有耗时；需要尽量避免对消息发送、接收产生影响。</p>
<h2 id="异步写入消息"><a href="#异步写入消息" class="headerlink" title="异步写入消息"></a>异步写入消息</h2><p>因此我把消息写入的过程异步完成，可以不影响真正的业务。</p>
<p>实现起来也挺简单，就是一个典型的生产者消费者模式。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c3128f910.jpg" alt=""></p>
<p>主线程收到消息之后直接写入队列，另外再有一个线程一直源源不断的从队列中取出数据后保存聊天记录。</p>
<p>大概的代码如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c3143be05.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c315b6c17.jpg" alt=""></p>
<hr>
<p>写入消息的同时会把消费消息的线程打开：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c317b8636.jpg" alt=""></p>
<p>而最终存放消息记录的策略，考虑后还是以最简单的方式存放在客户端，可以降低复杂度。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c31d716d4.jpg" alt=""></p>
<p>简单来说就是根据当前日期+用户名写入到磁盘里。</p>
<p>当客户端关闭时利用线程中断的方式停止了消费队列的线程。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c31f4438c.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c320d9a62.jpg" alt=""></p>
<p>这点的设计其实和 <code>logback</code> 写日志的方式比较类似，感兴趣的可以去翻翻 <code>logback</code> 的源码，更加详细。</p>
<h2 id="回调接口"><a href="#回调接口" class="headerlink" title="回调接口"></a>回调接口</h2><p>至于收到其他客户端发来的消息时则是利用之前预留的消息回调接口来写入日志。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c323439df.jpg" alt=""></p>
<p>收到消息后会执行自定义的回调接口。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c32569b6e.jpg" alt=""></p>
<p>于是在这个回调方法中实现写入逻辑即可，当后续还有其他的消息处理逻辑时也能在这里直接添加。</p>
<blockquote>
<p>当处理逻辑增多时最好是改为责任链模式，更加清晰易维护。</p>
</blockquote>
<h2 id="查找算法"><a href="#查找算法" class="headerlink" title="查找算法"></a>查找算法</h2><p>接下来是本文着重要讨论的一个查找算法，准确的说是一个前缀模糊匹配的算法。</p>
<p>实现的效果如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c32ac3397.jpg" alt=""></p>
<p>使用命令 <code>:qu prefix</code> 可以按照前缀的方式搜索用户信息。</p>
<p>当然在命令行中其实意义不大，但是在移动端中确是比较有用的。类似于微信按照用户名匹配：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c331b88d5.jpg" alt=""></p>
<blockquote>
<p>因为后期打算出一个移动端 APP，所以就先把这个功能实现了。</p>
</blockquote>
<p>从效果也看得出来：就是按照输入的前缀匹配字符串（目前只支持英文）。</p>
<p>在没有任何限制的条件下最快、最简单的实现方式可以直接把所有的字符串存放在一个容器中 （List、Set），查询时则挨个遍历；利用 <code>String.startsWith(&quot;prefix&quot;)</code> 进行匹配。</p>
<p>但这样会有几个问题：</p>
<ul>
<li>存储资源比较浪费，不管是 list 还是 Set 都会有额外的损耗。</li>
<li>查询效率较低，需要遍历集合后再遍历字符串的 <code>char</code> 数组（<code>String.startsWith</code> 的实现方式）。</li>
</ul>
<h3 id="字典树"><a href="#字典树" class="headerlink" title="字典树"></a>字典树</h3><p>基于以上的问题我们可以考虑下：</p>
<p>假设我需要存放 <code>java,javascript,jsp,php</code> 这些字符串时在 ArrayList 中会怎么存放？</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c333b6dad.jpg" alt=""></p>
<p>很明显，会是这样完整的存放在一个数组中；同时这个数组还可能存在浪费，没有全部使用完。</p>
<p>但其实仔细观察这些数据会发现有一些共同特点，比如 <code>java,javascript</code> 有共同的前缀 <code>java</code>;和 <code>jsp</code> 有共同的前缀 <code>j</code>。</p>
<p>那是否可以把这些前缀利用起来呢？这样就可以少存储一份。</p>
<p>比如写入 <code>java,javascript</code> 这两个字符串时存放的结构如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c33583002.jpg" alt=""></p>
<p>当再存入一个 <code>jsp</code> 时：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c33edb7ef.jpg" alt=""></p>
<p>最后再存入 <code>jsf</code> 时：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c340d4dd9.jpg" alt=""></p>
<p>相信大家应该已经看明白了，按照这样的存储方式可以节省很多内存，同时查询效率也比较高。</p>
<p>比如查询以 <code>jav</code> 开头的数据，只需要从头结点 <code>j</code> 开始往下查询，最后会查询到 <code>ava</code> 以及 <code>script</code> 这两个个结点，所以整个查询路径所经历的字符拼起来就是查询到的结果<code>java+javascript</code>。</p>
<p>如果以 <code>b</code> 开头进行查询，那第一步就会直接返回，这样比在 <code>list</code> 中的效率高很多。</p>
<p>但这个图还不完善，因为不知道查询到啥时候算是匹配到了一个之前写入的字符串。</p>
<blockquote>
<p>比如在上图中怎么知道 <code>j+ava</code> 是一个我们之前写入的 <code>java</code> 这个字符呢。</p>
</blockquote>
<p>因此我们需要对这种是一个<strong>完整字符串</strong>的数据打上一个标记：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c34277179.jpg" alt=""></p>
<p>比如这样，我们将 <code>ava、script、p、f</code> 这几个节点都换一个颜色表示。表明查询到这个字符时就算是匹配到了一个结果。</p>
<p>而查到 <code>s</code> 这个字符颜色不对，代表还需要继续往下查。</p>
<p>比如输入关键字 <code>js</code> 进行匹配时，当它的查询路径走到 <code>s</code> 这里时判断到 s 的颜色不对，所以不会把 <code>js</code> 作为一个匹配结果。而是继续往下查，发现有两个子节点 p、f 颜色都正确，于是把查询的路径 <code>jsp</code> 和 <code>jsf</code> 都作为一个匹配结果。</p>
<p>而只输入 j，则会把下面所有有色的字符拼起来作为结果集合。</p>
<blockquote>
<p>这其实就一个典型的字典树。</p>
</blockquote>
<h3 id="具体实现"><a href="#具体实现" class="headerlink" title="具体实现"></a>具体实现</h3><p>下面则是具体的代码实现，其实算法不像是实现一个业务功能这样好用文字分析；具体还是看源码多调试就明白了。</p>
<p>谈下几个重点的地方吧：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c349dd2bb.jpg" alt=""></p>
<p>字典树的节点实现，其中的 <code>isEnd</code> 相当于图中的上色。</p>
<p>利用一个 <code>Node[] children</code> 来存放子节点。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c34d8ea29.jpg" alt=""></p>
<p>为了可以区分大小写查询，所以子节点的长度相当于是 <code>26*2</code>。</p>
<h3 id="写入数据"><a href="#写入数据" class="headerlink" title="写入数据"></a>写入数据</h3><p><img src="https://i.loli.net/2019/05/08/5cd1c350b56da.jpg" alt=""></p>
<p>这里以一个单测为例，写入了三个字符串，那最终形成的数据结构如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c356cb710.jpg" alt=""></p>
<p>图中有与上图有几点不同：</p>
<ul>
<li>每个节点都是一个字符，这样树的高度最高为52。</li>
<li>每个节点的子节点都是长度为 52 的数组；所以可以利用数组的下标表示他代表的字符值。比如 0 就是大 A,26 则是小 a，以此类推。</li>
<li>有点类似于之前提到的<a href="https://crossoverjie.top/2018/11/26/guava/guava-bloom-filter/">布隆过滤器</a>，可以节省内存。</li>
</ul>
<p><code>debug</code> 时也能看出符合上图的数据结构：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c3646e24c.jpg" alt=""></p>
<p>所以真正的写入步骤如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c3699d6da.jpg" alt=""></p>
<ol>
<li>把字符串拆分为 char 数组，并判断大小写计算它所存放在数组中的位置 <code>index</code>。</li>
<li>将当前节点的子节点数组的 index 处新增一个节点。</li>
<li>如果是最后一个字符就将新增的节点置为最后一个节点，也就是上文的改变节点颜色。</li>
<li>最后将当前节点指向下一个节点方便继续写入。</li>
</ol>
<hr>
<p><img src="https://i.loli.net/2019/05/08/5cd1c36e26b18.jpg" alt=""><br><img src="https://i.loli.net/2019/05/08/5cd1c3740223e.jpg" alt=""></p>
<p>查询总的来说要麻烦一些，其实就是对树进行深度遍历；最终的思想看图就能明白。</p>
<p>所以在 cim 中进行模糊匹配时就用到了这个结构。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c37724b46.jpg" alt=""></p>
<p>字典树的源码在此处：</p>
<p><a href="https://github.com/crossoverJie/cim/blob/master/cim-common/src/main/java/com/crossoverjie/cim/common/data/construct/TrieTree.java" target="_blank" rel="external">https://github.com/crossoverJie/cim/blob/master/cim-common/src/main/java/com/crossoverjie/cim/common/data/construct/TrieTree.java</a></p>
<blockquote>
<p>其实利用这个结构还能实现判断某个前缀的单词是否在某堆数据里、某个前缀的单词出现的次数等。</p>
</blockquote>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>目前 <a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">cim</a> 还在火热内测中（虽然群里只有20几人）,感兴趣的朋友可以私聊我拉你入伙☺️ </p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c3816b687.jpg" alt=""></p>
<p>再没有新的 <code>BUG</code> 产生前会着重把这些功能完成了，不出意外下周更新 <code>cim</code> 的心跳重连等机制。</p>
<p>完整源码：</p>
<p><a href="https://github.com/crossoverJie/cim" target="_blank" rel="external">https://github.com/crossoverJie/cim</a></p>
<p>如果这篇对你有所帮助还请不吝转发。</p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/IM/" rel="tag">#IM</a>
          
            <a href="/tags/TrieTree/" rel="tag">#TrieTree</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/02/netty/cim01-started/" rel="next" title="为自己搭建一个分布式 IM(即时通讯) 系统">
                <i class="fa fa-chevron-left"></i> 为自己搭建一个分布式 IM(即时通讯) 系统
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/23/netty/cim03-heartbeat/" rel="prev" title="长连接的心跳及重连设计">
                长连接的心跳及重连设计 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#AI-模式"><span class="nav-number">2.</span> <span class="nav-text">AI 模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#聊天记录"><span class="nav-number">3.</span> <span class="nav-text">聊天记录</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#异步写入消息"><span class="nav-number">3.1.</span> <span class="nav-text">异步写入消息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#回调接口"><span class="nav-number">3.2.</span> <span class="nav-text">回调接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查找算法"><span class="nav-number">3.3.</span> <span class="nav-text">查找算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#字典树"><span class="nav-number">3.3.1.</span> <span class="nav-text">字典树</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#具体实现"><span class="nav-number">3.3.2.</span> <span class="nav-text">具体实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#写入数据"><span class="nav-number">3.3.3.</span> <span class="nav-text">写入数据</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2019/01/14/netty/cim02-v1.0.1/';
      var disqus_title = "为自己搭建一个分布式 IM 系统二【从查找算法聊起】";
      var disqus_url = 'http://crossoverjie.top/2019/01/14/netty/cim02-v1.0.1/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
